const express = require('express');
const app = express();
let url = require('url');
//跨域请求
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "content-type,content-length, authorization,\'origin\',X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header('Access-Control-Allow-Credentials', true);
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

//添加数据库模板依赖s
const models = require('../../db/models');
const {Op} = require("sequelize");//注入Op，用于多条件查询等等
const bodyParser = require('body-parser');
const path = require("path");
//时间格式设置所需要组件
//引入组件
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'public')));

//页面的入口，跳转到index页面，然后通过钩子函数，查询数据渲染页面
app.get('/login',function (req,res){
    res.type("html");
    res.sendFile("D:/Workspaces/IdeaWorkspaces/StudentSys/src/index.html");
})
//跳转course.html页面
app.get('/toCourse',function (req,res) {
    res.type("html");
    res.sendFile("D:/Workspaces/IdeaWorkspaces/StudentSys/src/course.html");
})
//跳转choice.html页面
app.get('/toChoice',function (req,res) {
    res.type("html");
    res.sendFile("D:/Workspaces/IdeaWorkspaces/StudentSys/src/choice.html");
})
//跳转detail.html页面
app.get('/toDetail',function (req,res) {
    res.type("html");
    res.sendFile("D:/Workspaces/IdeaWorkspaces/StudentSys/src/detail.html");
})
//刷新course.html页面数据
app.post('/show',async function (req,res){
    console.log("show");
    let limit = req.body.data.limit;
    let retList = await models.stu_course.findAndCountAll({
        limit
    });
    let list = retList.rows;
    let count = retList.count;
    res.json({
        list,
        count
    })
})
//模糊查询，分页查询
app.post('/query',async function (req,res){
    let getVal = req.body.data.val;
    let cols = req.body.data.cols;
    let limit = req.body.data.limit;
    console.log("query");
    let retList = await models.stu_course.findAndCountAll({
        where:{
            [Op.or]:[
                { id: getVal },
                {
                    name:{
                        [Op.like]:"%"+getVal+"%"
                    }
                }
            ]
        },
        offset:(cols-1)*limit,
        limit
    });
    let list = retList.rows;
    let count = retList.count;
    res.json({
        list,
        count
    })
})
//根据id查询，用于修改页面
app.get('/findById',async function (req,res){
    let id = req.query.id;
    console.log("findById");
    let one = await models.stu_course.findOne({
        where:{
            id
        }
    });
    res.json({
        one
    })
})
//根据id修改student表数据
app.get('/update',async function (req,res){
    let getCou = req.query;
    if (getCou != null || getCou.length>0){
        await models.stu_course.update({
                name: getCou.name,
                credit: getCou.credit,
                period: getCou.period,
                remark: getCou.remark
            }
            ,{
                where:{
                    id:getCou.id
                }
            });
    }
    res.type("html");
    res.sendFile("D:/Workspaces/IdeaWorkspaces/StudentSys/src/course.html");
})
//新增course表数据
app.get('/insert',async function (req,res) {
    let obj = req.query;
    models.stu_course.create({
        name:obj.name,
        credit:obj.credit,
        period:obj.period,
        remark:obj.remark
    })
    res.type("html");
    res.sendFile("D:/Workspaces/IdeaWorkspaces/StudentSys/src/course.html");
})
//根据id数组删除
app.post('/delete',async function (req, res) {
    console.log("delete");
    //如果查询有数据，则可以删除
    let idList = req.body.data.id;
    let one = await models.stu_course.findOne({
        where:{
            id:idList
        }
    });
    if (one != null){
        await models.stu_course.destroy({
            where:{
                id:{
                    [Op.in]:idList
                }
            }
        })
    }
    res.send({})
})
//异常处理
function error_handler(err,req,res,next){
    if (err){
        let {message} = err;
        res.status(500).json({
            message:message || "服务器异常"
        })
    }
}

app.use(error_handler);

//服务监听
app.listen(3001, ()=>{
    console.log("启动成功course!")
})